from django.db import models

from django.db import models
from utils.models import BaseModel
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature
from mall import settings


# Create your models here.
# 定义QQ身份（openid）与用户模型类User的关联关系
class OAuthQQUser(BaseModel):
    """
    QQ登录用户数据
    """
    user = models.ForeignKey('users.User', on_delete=models.CASCADE, verbose_name='用户')
    # db_index 是索引，用于快速查询数据
    openid = models.CharField(max_length=64, verbose_name='openid', db_index=True)

    class Meta:
        db_table = 'tb_oauth_qq'
        verbose_name = 'QQ登录用户数据'
        verbose_name_plural = verbose_name

    @classmethod
    def genericte_open_id_token(cls, openid):

        # 实例化序列器
        serializer = Serializer(settings.SECRET_KEY, 3600)

        # 编码
        token = serializer.dumps({'openid': openid})

        return token.decode()

    @classmethod
    def check_openid(cls, token):

        # 创建序列化
        serializer = Serializer(settings.SECRET_KEY, 3600)

        # 数据校验,需要进行try catch操作
        try:
            # 解码
            result = serializer.loads(token)
        except BadSignature:
            return None
        else:
            return result.get('openid')